import 'dart:async';
import 'dart:io';

import 'package:cave_flutter/routes/whl_app_pages.dart';
import 'package:flutter/animation.dart';
import 'package:get/get.dart';
import 'package:nim_core/nim_core.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../../common/chat_rtc_manager.dart';
import '../../../model/user_model.dart';
import '../../../network/whl_api.dart';
import '../../../utils/event_bus_utils.dart';
import '../../../utils/whl_dialog_util.dart';
import '../../../widgets/ls_love_progress_view.dart';

class Chat_call_ingLogic extends GetxController with GetTickerProviderStateMixin{

  late AnimationController animationController;
  late AnimationController progressAnimationController;
  StreamSubscription? rtcStatusSubscription;
  StreamSubscription? rtcNotificationSubscription;
  bool isCall = false;
  bool isVideo = false;
  int uid = 0;

  String toAccountId = "";

  UserModel? userModel;
  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    var a = Get.arguments;
    if (a != null) {
      uid = a["uid"]??0;
      isVideo = a["isVideoCall"]??false;
      isCall = a["isCall"]??false;
      toAccountId = a["toAccountId"]??"";
      userModel = a["userModel"];
      if (isCall) {
        ChatRTCManager.getInstance().initRtc(a["token"]??"", a["channelName"]??"", uid,isVideo: isVideo);
      }
    }
    if (userModel == null) {
      getAllUserInfo();
    }
    ChatRTCManager.getInstance().toAccountId = toAccountId;
    animationController = AnimationController(vsync: this,duration: const Duration(milliseconds: 1300));
    progressAnimationController = AnimationController(duration: const Duration(milliseconds: 4000), vsync: this);
    animationController.repeat();
    setupSubscription();
    update();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    animationController.stop();
    animationController.dispose();
    rtcStatusSubscription?.cancel();
    rtcNotificationSubscription?.cancel();
    super.onClose();
  }

  setupSubscription(){
    rtcStatusSubscription =
        EventBusUtils.getInstance().eventBus.on<RtcStatus>().listen((event) {
          // All events are of type UserLoggedInEvent (or subtypes of it).
          print("change 11111 --- ${event.status}");
          if (event.status == 1) {
            ChatRTCManager.getInstance().userModel = userModel;
            Get.offAndToNamed(Routes.chatCallPage);
          }else if (event.status == -1) {
            ChatRTCManager.getInstance().stopCall();
            Get.back();
          }
        });

    // rtcNotificationSubscription =
    //     EventBusUtils.getInstance().eventBus.on<CustomNotification>().listen((event) {
    //       // All events are of type UserLoggedInEvent (or subtypes of it).
    //       print("join start 22222");
    //       if (event.sessionId == toAccountId && event.content == "1") {
    //         // if (!ChatRTCManager.getInstance().isCallIng && isCall) {
    //         //   print("is call 2222");
    //         //
    //         // }
    //         joinRoom();
    //         // conversationListLogic.update();
    //       }
    //     });
  }

  getAllUserInfo() {
    List allIds = [toAccountId];
    WhlApi.batchReplaceUserInfo.post(allIds).then((value) {
      if (value.isSuccess()) {
        List data = value.data ?? [];
        List<UserModel> models =
        data.map((e) => UserModel.fromJson(e)).toList();
        userModel = models.first;
        update();
      }
    });
  }

  joinRoom({bool isJT = false}) async {
    // if (isJT) {
    //   sendCallJTNotification(toAccountId);
    // }
    bool hasPermission = await checkPermission();
    if (hasPermission) {
      print("join start 1111");
      var a = Get.arguments;
      ChatRTCManager.getInstance().initRtc(a["token"]??"", a["channelName"]??"", uid,isVideo: isVideo);
      ChatRTCManager.getInstance().userModel = userModel;
      Get.offAndToNamed(Routes.chatCallPage);
    }
  }


  Future<bool> checkPermission() async {
    //检查权限
    final permissions = [Permission.camera, Permission.microphone];
    if (Platform.isAndroid) {
      permissions.add(Permission.storage);
    }
    List<Permission> missed = [];
    for (var permission in permissions) {
      PermissionStatus status = await permission.status;
      if (status != PermissionStatus.granted) {
        missed.add(permission);
      }
    }

    bool allGranted = missed.isEmpty;
    if (!allGranted) {
      List<Permission> showRationale = [];
      for (var permission in missed) {
        bool isShown = await permission.shouldShowRequestRationale;
        if (isShown) {
          showRationale.add(permission);
        }
      }

      if (showRationale.isNotEmpty) {
        WhlDialogUtil.showConfirmDialog('您需要允许一些权限',
            isShowCancel: true, cancelAction: () {
              // Get.back();
            }, sureAction: () async {
              // Get.back();
              Map<Permission, PermissionStatus> allStatus = await missed.request();
              allGranted = true;
              for (var status in allStatus.values) {
                if (status != PermissionStatus.granted) {
                  allGranted = false;
                }
              }
            });
      } else {
        Map<Permission, PermissionStatus> allStatus = await missed.request();
        allGranted = true;
        for (var status in allStatus.values) {
          if (status != PermissionStatus.granted) {
            allGranted = false;
          }
        }
      }
    }
    return allGranted;
  }

  void backAction() {
    sendCallCancelMessage(toAccountId: toAccountId,isVideoCall: isVideo,isReceive: !isCall);
    if (isCall) {
      ChatRTCManager.getInstance().stopCall();
    }
    Get.back();
  }

}
